import base64
from captcha.views import CaptchaStore, captcha_image
from ninja import Router, Schema, Field
from utils.cj_response import SuccessResponse, ErrorResponse
from utils.md5 import md5_pass
from utils.captcha import verify
from utils.cj_jwt import create_token
from utils.request_util import save_login_log
from utils.usual import get_user_info_from_token
from system.models import *

router = Router()


@router.get("/test")
def test(request):
    data = {
        "data": "《CJIA520のADMIN》启动成功"
    }
    return SuccessResponse(msg=data)


@router.get("/captcha")
def captcha(request):
    """
    获取图片验证码
    :param request:
    :return:
    """
    CaptchaStore.remove_expired()  # 清理过期的验证码记录
    hashkey = CaptchaStore.generate_key()
    id = CaptchaStore.objects.filter(hashkey=hashkey).first().id
    imgage = captcha_image(request, hashkey)
    # 将图片转换为base64
    image_base = base64.b64encode(imgage.content)
    json_data = {"key": id, "image_base": "data:image/png;base64," + image_base.decode('utf-8')}
    return SuccessResponse(data=json_data)


class UserIn(Schema):
    username: str
    password: str
    nickname: str


@router.post("/register")
def create_user(request, payload: UserIn):
    """
    注册管理员用户
    :param request:
    :param payload:
    :return:
    """
    pass_md5 = md5_pass(payload.password)
    payload.password = pass_md5
    user = Users.objects.create(**payload.dict())
    data = {
        "id": user.id
    }
    return SuccessResponse(data=data)


class LoginIn(Schema):
    username: str = Field(None, alias="username")
    password: str = Field(None, alias="password")
    code: str = Field(None, alias="code")
    key: int = Field(None, alias="key")


@router.post("/login")
def login(request, payload: LoginIn):
    """
    后台用户登录
    :param request:
    :param payload: 登录参数
    :return:
    """
    # 开启验证码验证
    hashkey = CaptchaStore.objects.get(id=payload.key).hashkey
    if not verify(hashkey, payload.code):
        return ErrorResponse(msg="图片验证码错误")
    # 根据用户名查询用户信息
    user = Users.objects.filter(username=payload.username).values()
    if not user:
        return ErrorResponse(msg="用户不存在")
    md5_pwd = md5_pass(payload.password)
    if md5_pwd != user[0]['password']:
        return ErrorResponse(msg="密码不正确")
    if user[0]['status'] == 2:
        return ErrorResponse(msg="该账号已被禁用,请联系管理员")
    # 生成token
    jwt = create_token({"userId": user[0]['id']})
    token = f"Bearer {jwt}"
    request.user = user[0]
    del user[0]['password']
    user[0]['token'] = token
    # 开启token缓存
    if Token.objects.filter(userId=user[0]['id']).exists():
        Token.objects.filter(userId=user[0]['id']).update(token=user[0]['token'])
    else:
        Token(userId=user[0]['id'], token=user[0]['token']).save()
    save_login_log(request=request)
    return SuccessResponse(data=user[0], msg="登录成功")


@router.post("/logout")
def logout(request):
    """
    退出登录
    :param request:
    :return:
    """
    user_info = get_user_info_from_token(request)
    # 清除缓存
    Token.objects.filter(userId=user_info["userId"]).update(token="")
    return SuccessResponse(data="注销成功")


@router.get("/userinfo")
def get_userinfo(request):
    """
    登录用户信息
    :param request:
    :return:
    """
    user_info = get_user_info_from_token(request)
    user = list(Users.objects.filter(id=user_info['userId']).values())[0]
    del user['password']
    return SuccessResponse(data=user, msg="获取成功")
